package com.sanqing.iframe;
import com.sanqing.model.Operator;
import com.sanqing.dao.Dao;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ReaderAddFrame extends JInternalFrame {
    private JTextField isbnField, nameField, identityField, telField, confirmPasswordField;
    private JComboBox<String> sexCombo, typeCombo;
    private JSpinner ageSpinner;
    private JPasswordField passwordField;
    private JFormattedTextField dateField;
    private JButton addButton, closeButton;
    private static final Map<Integer, String> ID_TYPE_MAP = new HashMap<>();
    private static final Map<Integer, Integer> MAX_BORROW_MAP = new HashMap<>();
    static {
        ID_TYPE_MAP.put(1, "本科生");
        ID_TYPE_MAP.put(2, "研究生");
        ID_TYPE_MAP.put(3, "教职工");
        MAX_BORROW_MAP.put(1, 5);
        MAX_BORROW_MAP.put(2, 10);
        MAX_BORROW_MAP.put(3, 20);
    }
    public ReaderAddFrame() {
        super();
        setTitle("用户信息添加");
        setLayout(new BorderLayout());
        setSize(600, 500);
        setBounds(20, 100, 850, 406);
        setIconifiable(true);
        setClosable(true);

        JPanel mainPanel = new JPanel(new GridLayout(11, 2, 10, 10));
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        // 读者编号
        JLabel isbnLabel = new JLabel("读者编号：");
        isbnField = new JTextField();
        mainPanel.add(isbnLabel);
        mainPanel.add(isbnField);
        // 姓名
        JLabel nameLabel = new JLabel("姓名：");
        nameField = new JTextField();
        mainPanel.add(nameLabel);
        mainPanel.add(nameField);
        // 性别
        JLabel sexLabel = new JLabel("性别：");
        sexCombo = new JComboBox<>(new String[]{"男", "女"});
        mainPanel.add(sexLabel);
        mainPanel.add(sexCombo);
        // 年龄
        JLabel ageLabel = new JLabel("年龄：");
        ageSpinner = new JSpinner(new SpinnerNumberModel(18, 1, 100, 1));
        mainPanel.add(ageLabel);
        mainPanel.add(ageSpinner);
        // 证件号码
        JLabel identityLabel = new JLabel("证件号码：");
        identityField = new JTextField();
        identityField.setDocument(new NumberDocument(10));
        mainPanel.add(identityLabel);
        mainPanel.add(identityField);
        // 有效期
        JLabel dateLabel = new JLabel("有效期（yyyy-MM-dd）：");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateField = new JFormattedTextField(dateFormat);
        mainPanel.add(dateLabel);
        mainPanel.add(dateField);
        // 证件类型
        JLabel typeLabel = new JLabel("证件类型：");
        typeCombo = new JComboBox<>(ID_TYPE_MAP.values().toArray(new String[0]));
        typeCombo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateMaxBorrow();
            }
        });
        mainPanel.add(typeLabel);
        mainPanel.add(typeCombo);
        // 电话号码
        JLabel telLabel = new JLabel("电话号码：");
        telField = new JTextField();
        telField.setDocument(new NumberDocument(11));
        mainPanel.add(telLabel);
        mainPanel.add(telField);
        // 密码
        JLabel passwordLabel = new JLabel("密码：");
        passwordField = new JPasswordField();
        mainPanel.add(passwordLabel);
        mainPanel.add(passwordField);

        // 确认密码
        JLabel confirmPasswordLabel = new JLabel("确认密码：");
        confirmPasswordField = new JPasswordField();
        mainPanel.add(confirmPasswordLabel);
        mainPanel.add(confirmPasswordField);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        addButton = new JButton("添加");
        addButton.addActionListener(new AddOperatorActionListener());
        closeButton = new JButton("关闭");
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        buttonPanel.add(addButton);
        buttonPanel.add(closeButton);

        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
        setVisible(true);
    }

    private void updateMaxBorrow() {
        int selectedIndex = typeCombo.getSelectedIndex() + 1;
    }

    private class AddOperatorActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String isbn = isbnField.getText().trim();
            String name = nameField.getText().trim();
            String sex = (String) sexCombo.getSelectedItem();
            int age = (int) ageSpinner.getValue();
            String identity = identityField.getText().trim();
            String dateStr = dateField.getText().trim();
            int type = typeCombo.getSelectedIndex() + 1;
            String tel = telField.getText().trim();
            String password = new String(passwordField.getPassword());
            String confirmPassword = confirmPasswordField.getText().trim();
            if (isbn.isEmpty() || name.isEmpty() || identity.isEmpty() || dateStr.isEmpty()
                    || tel.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
                JOptionPane.showMessageDialog(ReaderAddFrame.this, "所有字段都必须填写", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            if (!password.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(ReaderAddFrame.this, "两次输入的密码不一致", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (!identity.matches("\\d{10}")) {
                JOptionPane.showMessageDialog(ReaderAddFrame.this, "证件号码必须是10位数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (!tel.matches("\\d{11}")) {
                JOptionPane.showMessageDialog(ReaderAddFrame.this, "电话号码必须是11位数字", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            Date date;
            try {
                date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(ReaderAddFrame.this, "有效期格式必须为 yyyy-MM-dd", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (isISBNExists(isbn)) {
                JOptionPane.showMessageDialog(ReaderAddFrame.this, "该读者编号已存在，请重新输入", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 检查证件号码是否唯一
            if (isIdentityExists(identity)) {
                JOptionPane.showMessageDialog(ReaderAddFrame.this, "该证件号码已存在，请重新输入", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            Operator operator = new Operator();
            operator.setISBN(isbn);
            operator.setName(name);
            operator.setSex(sex);
            operator.setAge(String.valueOf(age));
            operator.setIndentityCard(identity);
            operator.setDate(date);
            operator.setZj(type);
            operator.setTel(tel);
            operator.setMaxNum(String.valueOf(MAX_BORROW_MAP.get(type)));
            operator.setGrade(0);
            operator.setPassword(password);

            String sql = "INSERT INTO tb_operator (R_ISBN, name, sex, age, identityCard, date, zj, tel, maxNum, admin, password) " +
                    "VALUES ('" + isbn + "', '" + name + "', '" + sex + "', '" + age + "', '" + identity + "', '" + dateStr + "', " + type + ", '" + tel + "', '" + MAX_BORROW_MAP.get(type) + "', '0', '" + password + "')";
            int result = Dao.executeUpdate(sql);

            if (result > 0) {
                JOptionPane.showMessageDialog(ReaderAddFrame.this, "用户信息添加成功", "添加成功", JOptionPane.INFORMATION_MESSAGE);
                // 清空输入框
                isbnField.setText("");
                nameField.setText("");
                identityField.setText("");
                dateField.setText("");
                telField.setText("");
                passwordField.setText("");
                confirmPasswordField.setText("");
            } else {
                JOptionPane.showMessageDialog(ReaderAddFrame.this, "用户信息添加失败", "添加失败", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private boolean isISBNExists(String isbn) {
        String sql = "SELECT COUNT(*) FROM tb_operator WHERE R_ISBN = '" + isbn + "'";
        ResultSet rs = Dao.executeQuery(sql);
        try {
            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
    
    private boolean isIdentityExists(String identity) {
        String sql = "SELECT COUNT(*) FROM tb_operator WHERE identityCard = '" + identity + "'";
        ResultSet rs = Dao.executeQuery(sql);
        try {
            if (rs.next()) {
                return rs.getInt(1) > 0;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
    
    private class NumberDocument extends PlainDocument {
        private int maxLength;

        public NumberDocument(int maxLength) {
            this.maxLength = maxLength;
        }

        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if (str == null) return;
            if ((getLength() + str.length()) <= maxLength && str.matches("\\d*")) {
                super.insertString(offs, str, a);
            }
        }
    }
}